/**
 * Copyright (c) 2018, Alex. All rights reserved.
 */
package com.oschina.bottle.utils;

import com.oschina.bottle.utils.validator.RegExpValidator;
import java.util.Random;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;

/**
 * 整合一些常用的方法
 *
 * @author <a href="mailto:zhongchao@gegejia.com">zhong</a>
 * @version 1.0 2018/1/10
 * @since 1.0
 */
public class CommonUtils {

    /**
     * 生成指定长度的随机数字
     *
     * @return 验证通过返回true
     */
    public static String generateRandomCode(int length) {
        String result = "";
        for (int i = 0; i < length; i++) {
            result += new Random().nextInt(9);
        }
        return result;
    }

    /**
     * 隐藏字符串中的部分
     */
    public static String hideKeyword(String value) {
        if (StringUtils.isBlank(value) || value.length() < 2) {
            return value != null ? value + "*" : "*";
        }

        int length = value.length();
        int index = value.lastIndexOf("@");
        if (RegExpValidator.validate(RegExpValidator.MOBILE_REG, value)) {
            return value.substring(0, 3) + "****" + value.substring(length - 4, length);
        }
        if (value.length() < 7) {
            value = value.substring(0, length / 2) + "**" + value
                .substring((length % 2 == 0) ? length / 2 + 1 : length / 2 + 1, length);
        } else if (index > -1) {
            value = value.substring(0, (index > 3) ? 3 : index) + "***" + value
                .substring(index, length);
        } else {
            value = value.substring(0, 3) + "***" + value.substring(length - 3, length);
        }
        return value;
    }

    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}
